﻿using PhoneStoreWeb.Models;
using System;
using System.Data.Entity.Validation;
using System.Linq;
using System.Web.Mvc;

namespace PhoneStoreWeb.Controllers
{
    public class CheckoutController : Controller
    {
        PhoneStoreEntities storeDB = new PhoneStoreEntities();

        public ActionResult Index()
        {
            ShoppingCartModel cart = ShoppingCartModel.GetCart(this.HttpContext);
            if (ShoppingCartController.GetTotalProducts(cart) == 0)
            {
                return RedirectToAction("Index", "ShoppingCart");
            }
            return View();
        }
        
        [HttpPost]
        public ActionResult Index(ProductOrder order)
        {
            ShoppingCartModel cart = ShoppingCartModel.GetCart(this.HttpContext);
            if (storeDB.ProductOrders.Count() == 0)
            {
                order.OrderID = 1;
            }
            else
            {
                order.OrderID = storeDB.ProductOrders.OrderByDescending(o => o.OrderID).FirstOrDefault().OrderID + 1;
            }
            order.OrderDate = DateTime.Now.Date;
            order.UserName = (User.Identity.IsAuthenticated) ? User.Identity.Name : cart.ShoppingCartId;
            if (TryUpdateModel(order))
            {
                storeDB.ProductOrders.Add(order);
                storeDB.SaveChanges();
                this.CreateOrderDetails(cart, order);
                return RedirectToAction("CheckoutSuccessfully", new { id = order.OrderID });
            }
            else
            {
                return View(order);
            }
        }

        public ActionResult CheckoutSuccessfully(int id)
        {
            var order = storeDB.ProductOrders.FirstOrDefault(o => o.OrderID == id);
            if (order == null)
            {
                return RedirectToAction("Index");
            }
            var orderDetails = storeDB.ProductOrderDetails.Where(o => o.OrderID == id);
            var viewModel = new CheckoutViewModel
            {
                Order = order,
                OrderDetails = orderDetails.ToList()
            };
            return View(viewModel);
        }
        
        // Create order details for this cart based on order
        public void CreateOrderDetails(ShoppingCartModel cart, ProductOrder order)
        {
            var _order = storeDB.ProductOrders.FirstOrDefault(o => o.OrderID == order.OrderID);
            decimal orderTotal = 0;
            var cartItems = storeDB.Carts.Where(c => c.CartID == cart.ShoppingCartId);
            foreach (var cartItem in cartItems)
            {
                if (cartItem.Product.IsPromotional)
                {
                    var orderDetails = new ProductOrderDetail
                    {
                        ProductID = cartItem.Product.ProductID,
                        OrderID = order.OrderID,
                        UnitPrice = (int)cartItem.Product.RetailPrice * (100 - (int)cartItem.Product.Promotions.Last(p => p.ProductID == cartItem.ProductID).Percentage) / 100,
                        Quantity = cartItem.Quantity
                    };
                    storeDB.ProductOrderDetails.Add(orderDetails);
                    orderTotal += orderDetails.UnitPrice * orderDetails.Quantity;
                }
                else
                {
                    var orderDetails = new ProductOrderDetail
                    {
                        ProductID = cartItem.Product.ProductID,
                        OrderID = order.OrderID,
                        UnitPrice = cartItem.Product.RetailPrice,
                        Quantity = cartItem.Quantity
                    };
                    storeDB.ProductOrderDetails.Add(orderDetails);
                    orderTotal += orderDetails.UnitPrice * orderDetails.Quantity;
                }
                // Update quantity of product
                cartItem.Product.Quantity -= cartItem.Quantity;
                if (cartItem.Product.Quantity <= 0)
                {
                    cartItem.Product.IsHidden = true;
                }
            }
            _order.Total = orderTotal;            
            storeDB.SaveChanges();
            // Empty the shopping cart
            ShoppingCartController.EmptyCart(this.HttpContext);
        }
    }
}